package com.zyk.leetcode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author zhangsan
 * @date 2021/4/15 11:24
 */
public class C897 {

    // https://leetcode-cn.com/problems/increasing-order-search-tree/
    public TreeNode increasingBST(TreeNode root) {
        TreeNode ans = new TreeNode(0);
        cur = ans;
        inorder(root);
        return ans.right;
    }

    TreeNode cur;
    public void inorder(TreeNode node) {
        if (node == null) return;
        inorder(node.left);
        node.left = null;
        cur.right = node;
        cur = node;
        inorder(node.right);
    }

    // for test
    public static void main(String[] args) {
        C897 test = new C897();

        TreeNode a = new TreeNode(5);
        a.left = new TreeNode(3);
        a.right = new TreeNode(6);
        a.left.left = new TreeNode(2);
        a.left.right = new TreeNode(4);
        a.left.left.left = new TreeNode(1);
        a.right.right = new TreeNode(8);
        a.right.left = new TreeNode(7);
        a.right.right = new TreeNode(9);

        TreeNode root = test.increasingBST(a);
        print(root);
    }

    private static void print(TreeNode root) {
        // 按层遍历
        if(root == null) return;
        TreeNode end = root, nextEnd = root;
        Queue<TreeNode> queue = new LinkedList<>(){{ add(root); }};
        TreeNode cur;
        while (!queue.isEmpty()) {
            cur = queue.poll();
            if(cur.left != null) {
                queue.add(cur.left);
                nextEnd = cur.left;
            }
            if(cur.right != null) {
                queue.add(cur.right);
                nextEnd = cur.right;
            }
            System.out.print(cur.val + "\t");
            if(cur == end) {
                System.out.println();
                end = nextEnd;
            }
        }
    }

}
